<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use think\Validate;
use addons\epay\library\Service;
use Exception;

/**
 * 卖家工具/修改个人信息
 */
class Replace extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];




    /**
     * @ApiTitle    (修改个人信息页面)
     * @ApiSummary  (修改个人信息页面)
     * @ApiMethod   (POST)
     * @ApiRoute    (api/Replace/center)
     * @ApiHeaders	(name=token, type=string, required=true, description="请求的Token")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    "code": 1,
    "msg": "ok",
    "time": "1627553755",
    "data": {
    "id": 7,
    "account": 用户名,
    "nickname": 昵称,
    }
     * })
     */
    public function center()
    {
        $token = $this->request->header('token');
        $id = Db::name('personal')->where('token',$token)->value('id');
        $this->is_login($token);
        $res = Db::name('personal')->field('id,account,nickname')->where('id',$id)->find();
        $this->success('ok',$res);
    }

    /**
     * @ApiTitle    (个人信息执行修改)
     * @ApiSummary  (个人信息执行修改)
     * @ApiMethod   (POST)
     * @ApiRoute    (api/Replace/centerInfo)
     * @ApiHeaders	(name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="nickname", type="varchar", required=false, description="1:待支付 3:交易中 5:已完成 7:已取消")
     * @ApiParams   (name="sex", type="varchar", required=false, description="性别 0未知 1男 2女")
     * @ApiParams   (name="birthday", type="varchar", required=false, description="生日")
     * @ApiParams   (name="urgency_phone", type="varchar", required=false, description="应急手机")
     * @ApiParams   (name="urgency_qq", type="varchar", required=false, description="应急qq")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    "code": 1,
    "msg": "修改信息成功",
    "time": "1627553755",

     * })
     */
    public function centerInfo()
    {
        $token = $this->request->header('token');
        $id = Db::name('personal')->where('token',$token)->value('id');
        $this->is_login($token);
        $nickname = $this->request->post('nickname');
        $sex = $this->request->post('sex');
        $birthday = $this->request->post('birthday');
        $urgency_phone = $this->request->post('urgency_phone');
        $urgency_qq = $this->request->post('urgency_qq');
        $res = [
            'nickname'  =>  $nickname,
            'sex'   =>  $sex,
            'birthday'  =>  $birthday,
            'urgency_phone' =>  $urgency_phone,
            'urgency_qq'    =>  $urgency_qq
        ];
        $data = Db::name('personal')->where('id',$id)->update($res);
        if ($data) {
            $this->success('修改信息成功');
        } else {
            $this->error('修改信息失败');
        }
    }



    /**
     * @ApiTitle    (卖家工具)
     * @ApiSummary  (卖家工具)
     * @ApiMethod   (POST)
     * @ApiRoute    (api/Replace/batch)
     * @ApiHeaders	(name=token, type=string, required=true, description="请求的Token")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    "code": 1,
    "msg": "ok",
    "time": "1627553755",

     * })
     */
    public function batch()
    {
        $token = $this->request->header('token');
        $id = Db::name('personal')->where('token',$token)->value('id');
        $this->is_login($token);
        $user = Db::name('personal')->where('id',$id)->find();
        if ($user['shopset'] == 0 && $user['vipset'] != 1 && $user['receset'] != 1) {
            $this->error('您没有开通此权限,请联系管理员后操作');
        }
        $res = Db::name('game')->field('id,game')->where('status','normal')->select();
        $this->success('ok',$res);
    }


    /**
     * @ApiTitle    (卖家工具---选择模板)
     * @ApiSummary  (卖家工具---选择模板)
     * @ApiMethod   (POST)
     * @ApiRoute    (api/Replace/batchList)
     * @ApiParams   (name="id", type="varchar", required=false, description="游戏id")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    "code": 1,
    "msg": "ok",
    "time": "1627553755",
    "data":
    "type": [
    {
    "id": 32,
    "name": 物品类型名,
    "buy_type": [
    {
    "id": 1,
    "name": 交易类型
    }
    ]
    }
    ],
     * })
     */
    public function batchList()
    {
        $id = $this->request->post('id');
        $map['game_id'] = $id;
        $map['gt_id'] = 5;
        $map['status'] = 'normal';
        $res['type'] = Db::name('game_info')->field('id,name')->where($map)->select();
        foreach ($res['type'] as $k=>$v) {
            if ($v['name'] == '账号') {
                $res['type'][$k]['buy_type'][] = ['id'=>1,'name'=>'平台代发'];
            } else {
                $res['type'][$k]['buy_type'][] = ['id'=>1,'name'=>'平台代发'];
                $res['type'][$k]['buy_type'][] = ['id'=>2,'name'=>'卖家发货'];
            }
        }
        $this->success('ok',$res);
    }




    /**
     * @ApiTitle    (卖家工具---下载模板)
     * @ApiSummary  (卖家工具---下载模板)
     * @ApiMethod   (POST)
     * @ApiRoute    (api/Replace/model)
     * @ApiHeaders	(name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="id", type="varchar", required=false, description="游戏id")
     * @ApiParams   (name="name", type="varchar", required=false, description="物品类型")
     * @ApiParams   (name="buy_type", type="varchar", required=false, description="交易类型1平台代发2卖家发货")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    "code": 1,
    "msg": "ok",
    "time": "1627553755",

     * })
     */
    public function model()
    {
        $token = $this->request->header('token');
        $uid = Db::name('personal')->where('token',$token)->value('id');
        $this->is_login($token);
        $id = $this->request->post('id');
        $name = $this->request->post('name');
        $buy_type = $this->request->post('buy_type');
        $user = Db::name('personal')->where('id',$uid)->find();
        if ($user['shopset'] == 1 && $name != '账号') {
            $this->error('您没有开通此权限,请联系管理员后操作');
        } elseif ($user['shopset'] == 2 && $name == '账号') {
            $this->error('您没有开通此权限,请联系管理员后操作');
        } elseif ($user['shopset'] == 0) {
            $this->error('您没有开通此权限,请联系管理员后操作');
        }
        if ($name == '账号') {
            $class = 1;
        } else {
            $class = 2;
        }
        $map['game_id'] = $id;
        $map['class_type'] = $class;
        $map['buy_type'] = $buy_type;
        $res = Db::name('game_model')->where($map)->find();
        if ($res) {
            $url = config('api_image_url') . $res['model'];
            $this->success('ok',$url);
        } else {
            $this->error('抱歉,没有此类模板');
        }
    }


    /**
     * @ApiTitle    (卖家工具---商品类型)
     * @ApiSummary  (卖家工具---商品类型)
     * @ApiMethod   (POST)
     * @ApiRoute    (api/Replace/batchType)
     * @ApiHeaders	(name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="type", type="varchar", required=false, description="1:发布商品 2:出售中商品 3:下架商品")
     * @ApiParams   (name="id", type="varchar", required=false, description="游戏id")
     * @ApiParams   (name="goods_type", type="varchar", required=false, description="物品类型名id")
     * @ApiParams   (name="buy_type", type="varchar", required=false, description="交易类型1平台代发2卖家发货")
     * @ApiParams   (name="havetime", type="varchar", required=false, description="有效期")
     * @ApiParams   (name="mobile", type="varchar", required=false, description="手机号")
     * @ApiParams   (name="qq", type="varchar", required=false, description="QQ")
     * @ApiParams   (name="arr", type="varchar", required=false, description="json数组")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    "code": 1,
    "msg": "ok",
    "time": "1627553755",

     * })
     */
    public function batchType()
    {
        $token = $this->request->header('token');
        $id = Db::name('personal')->where('token',$token)->value('id');
        $this->is_login($token);
        $type = $this->request->post('type');
        $gid = $this->request->post('id');
        $goods_type = $this->request->post('goods_type');
        $buy_type = $this->request->post('buy_type');
        $map['uid'] = $id;
        $map['stock'] = ['gt',0];
        if (!empty($gid)){
            $map['gameid'] = $gid;
        }
        if (!empty($goods_type)){
            $map['goods_type'] = $goods_type;
        }
        if (!empty($buy_type)){
            $map['method'] = $buy_type;
        }
        if ($type == 1) {
            $mobile = $this->request->post('mobile');
            $arr = $this->request->post('arr');
            $qq = $this->request->post('qq');
            $havetime = $this->request->post('havetime');
            $this->batchAdd($id,$arr,$mobile,$qq,$havetime);
        } elseif ($type == 2) {
            $map['status'] = 1;
            $res = Db::name('goods')
                ->field('id,createtime,area,server,type_name,goods_sn,method,title,stock,price,status,gamename,method')
                ->where($map)
                ->paginate(10);
            $this->success('ok',$res);
        } else {
            $map['status'] = 2;
            $res = Db::name('goods')
                ->field('id,createtime,area,server,type_name,goods_sn,method,title,stock,price,status,gamename,method')
                ->where($map)
                ->paginate(10);
            $this->success('ok',$res);
        }
    }




    /**
     * @ApiTitle    (商家服务)
     * @ApiSummary  (商家服务)
     * @ApiMethod   (POST)
     * @ApiRoute    (api/Replace/batchOff)
     * @ApiHeaders	(name=token, type=string, required=true, description="请求的Token")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    "code": 1,
    "msg": "ok",
    "time": "1627553755",

     * })
     */
    public function batchOff()
    {
        $token = $this->request->header('token');
        $id = Db::name('personal')->where('token',$token)->value('id');
        $this->is_login($token);
        $res = Db::name('personal')->field('qq,shopset,vipset,receset')->where('id',$id)->find();
        $this->success('ok',$res);
    }






    public function batchAdd($id,$arr,$mobile,$qq,$havetime)
    {
        $arr = htmlspecialchars_decode($arr);
        $arr = json_decode($arr,true);
        $res = [];
        $sku = [];
        $info = [];
        $user = Db::name('personal')->where('id',$id)->value('shopset');
        if ($user == 0) {
            $this->error('您的权限不能批量上架此商品');
        }
        foreach ($arr as $k=>$v) {
            $game = Db::name('game')->where('game',$v['name'])->value('id');
            $line = $k+1;
            if (empty($game)) {
                $this->error('第'.$line.'行游戏不匹配');
            }
            $goodsType = Db::name('game_info')->where('game_id',$game)->where('name',$v['type'])->where('status','normal')->value('id');
            if (empty($goodsType)) {
                $this->error('第'.$line.'行物品类型不匹配');
            }
            if ($v['method'] != '平台代发' && $v['method'] != '卖家发货') {
                $this->error('第'.$line.'行交易类型不匹配');
            }
            $areaId = Db::name('game_info')->where('game_id',$game)->where('name',$v['area'])->where('status','normal')->value('id');
            if (empty($areaId)) {
                $this->error('第'.$line.'行游戏区不匹配');
            }
            $serverId = Db::name('game_info')->where('game_id',$game)->where('name',$v['server'])->where('status','normal')->value('id');
            if (empty($serverId)) {
                $this->error('第'.$line.'行游戏服务器不匹配');
            }
            $crossId = Db::name('game_info')->where('id',$serverId)->value('cross');
            $cross = Db::name('gamecross')->where('id',$crossId)->value('name');
            $account = array_key_exists('游戏账号',$v);
            $password = array_key_exists('游戏密码',$v);
            $second_pwd = array_key_exists('二级密码',$v);
            $ware_pwd = array_key_exists('仓库密码',$v);
            $storage = array_key_exists('物品存放处',$v);
            $rank = array_key_exists('角色等级',$v);
            $roleName = array_key_exists('游戏角色名称',$v);
            $coin_type = array_key_exists('交易方式',$v);
            $job = array_key_exists('职业',$v);
            $punish = array_key_exists('处罚记录',$v);
            $wallow = array_key_exists('有无防沉迷',$v);
            $credit = array_key_exists('信用分',$v);
            if ($account == true) {
                $account = $v['游戏账号'];
                if (!Validate::regex($account, '/^\d{5}/')) {
                    $this->error(__('第'.$line.'行请填写正确的游戏账号'));
                }
            } else {
                $account = '';
            }
            if ($password == true) {
                $password = $v['游戏密码'];
                if (!Validate::is($password, 'require')) {
                    $this->error(__('第'.$line.'行请正确填写游戏密码'));
                }
                if ($password !== $v['确认游戏密码']) {
                    $this->error(__('第'.$line.'行请确保密码一致'));
                }
            } else {
                $password = '';
            }
            if ($second_pwd == true) {
                $second_pwd = $v['二级密码'];
                if (!Validate::regex($second_pwd, '^\d{1,6}$')) {
                    $this->error(__('第'.$line.'行请填写正确的二级密码'));
                }
            } else {
                $second_pwd = '';
            }
            if ($ware_pwd == true) {
                $ware_pwd = $v['仓库密码'];
            } else {
                $ware_pwd = '';
            }
            if ($storage == true) {
                $storage = $v['物品存放处'];
            } else {
                $storage = '';
            }
            if ($rank == true) {
                if (!Validate::regex($rank, '^100$|^(\d|[1-9]\d)$')) {
                    $this->error(__('第'.$line.'请正确填写角色等级'));
                }
            }
            if ($roleName == true) {
                if (!Validate::is($roleName, 'require')) {
                    $this->error(__('第'.$line.'行请正确填写游戏角色名称'));
                }
            }
            if ($coin_type == true) {
                if (!Validate::is($coin_type, 'require')) {
                    $this->error(__('第'.$line.'行请正确填写交易方式'));
                }
            }
            if ($job == true) {
                if (!Validate::is($job, 'require')) {
                    $this->error(__('第'.$line.'行请正确填写职业'));
                }
            }
            if ($punish == true) {
                if (!Validate::is($punish, 'require')) {
                    $this->error(__('第'.$line.'行请正确填写处罚记录'));
                }
            }
            if ($wallow == true) {
                if (!Validate::is($wallow, 'require')) {
                    $this->error(__('第'.$line.'行请正确填写有无防沉迷'));
                }
            }
            if ($credit == true) {
                if (!Validate::is($credit, 'require')) {
                    $this->error(__('第'.$line.'行请正确填写信用分'));
                }
            }
            if ($v['type'] == '账号') {
                if ($user == 2) {
                    $this->error('您的权限不能批量上架此商品');
                }
                $method = 1;
                $class_type = 1;
                $images = $v['img'];
                $img = explode(',',$images);
                $image = $img[0];
                $stock = 1;
                $safe = 1;
                $coin_type = 4;
                $coin_ratio = 0;
                $coin = 0;
                $desc = $v['账号描述'];
                if (!Validate::is($desc, 'require')) {
                    $this->error(__('第'.$line.'行请正确填写账号描述'));
                }
                $title = $v['商品标题'];
                if ($title == true) {
                    if (!Validate::is($title, 'require')) {
                        $this->error(__('第'.$line.'行请正确填写商品标题'));
                    }
                }
                $fee = Db::name('server')->where('id',1)->find();
                $price = $v['price']*(1+$fee['service']);
                $gameType = Db::name('game')->where('game',$v['name'])->value('type');
                if ($gameType == 'mobile') {
                    $plat = $v['游戏平台'];
                    $platId = Db::name('game_info')->where('game_id',$game)->where('name',$v['游戏平台'])->where('status','normal')->value('id');
                    if (empty($platId)) {
                        $this->error('第'.$line.'行游戏平台不匹配');
                    }
                    $operator = $v['运营商'];
                    $operatorId = Db::name('game_info')->where('game_id',$game)->where('name',$v['运营商'])->where('status','normal')->value('id');
                    if (empty($operatorId)) {
                        $this->error('第'.$line.'行运营商不匹配');
                    }
                } else {
                    $plat = '';
                    $platId = '';
                    $operator = '';
                    $operatorId = '';
                }

            } else {
                if ($user == 1) {
                    $this->error('您的权限不能批量上架此商品');
                }
                if ($v['method'] == '平台代发') {
                    $method = 1;
                } else {
                    $method = 2;
                }
                $class_type = 2;
                $images = Db::name('game')->where('id',$game)->value('w_image');
                $image = Db::name('game')->where('id',$game)->value('image');
                $stock = $v['发布件数'];
                if ($stock <= 0) {
                    $this->error(__('第'.$line.'行您发布件数不足'));
                } elseif ($stock > 10000) {
                    $this->error(__('第'.$line.'行您发布件数超过10000上限'));
                }
                $price = $v['price'];
                if ($price <= 0) {
                    $this->error(__('第'.$line.'行您发布价格不足'));
                } elseif ($price > 50000) {
                    $this->error(__('第'.$line.'行您发布价格超过50000上限'));
                }
                $coin_ratio = $v['商品数量'];
                if ($coin_ratio <= 0) {
                    $this->error(__('第'.$line.'行您发布商品数量不足'));
                } elseif ($coin_ratio > 10000000000) {
                    $this->error(__('第'.$line.'行您发布商品数量超过一百亿上限'));
                }
                $coin = $v['商品数量']/$v['price'];
                $title = '【'.$coin_type.'交易】'.$v['price'].'元='.$v['商品数量'].'万金';
                if ($coin_type == '邮寄') {
                    $coin_type = 1;
                } elseif ($coin_type == '拍卖') {
                    $coin_type = 2;
                } else {
                    $coin_type = 3;
                }
                $safe = 3;
                $desc = '';
                $plat = '';
                $platId = '';
                $operator = '';
                $operatorId = '';
            }
            $a1 = [
                'goods_class_type'  =>  $class_type,
                'goods_sn'  =>  $this->getRefundSn($v['snum']),
                'uid'   =>  $id,
                'gameid'    =>  $game,
                'gamename'  =>  $v['name'],
                'desc'  =>  $desc,
                'image' =>  $image,
                'images'    =>  $images,
                'status'    =>  1,
                'stock' =>  $stock,
                'method'    =>  $method,
                'goods_type'    =>  $goodsType,
                'type_name' =>  $v['type'],
                'title' =>  $title,
                'price' =>  $price,
                'plat_id'   =>  $platId,
                'plat'  =>  $plat,
                'operator_id'   =>  $operatorId,
                'operator'   =>  $operator,
                'area_id'   =>  $areaId,
                'area'   =>  $v['area'],
                'server_id'   =>  $serverId,
                'server'   =>  $v['server'],
                'cross_id'   =>  $crossId,
                'cross'   =>  $cross,
                'is_safe'   =>  $safe,
                'g_account'   =>  $account,
                'g_password'   =>  $password,
                'havetime' =>  time()+86400*$havetime,
                'mobile'    =>  $mobile,
                'qq'    =>  $qq,
                'coin_type'    =>  $coin_type,
                'coin'    =>  $coin_ratio,
                'coin_ratio'    =>  $coin,
                'createtime'    =>  time(),
                'second_pwd'    =>  $second_pwd,
                'ware_pwd'  =>  $ware_pwd,
                'storage'   =>  $storage
            ];

            $attr = array_keys($v);
            foreach ($attr as $kk=>$vv) {
                if (preg_match("/\s\s/", $vv)) {
                    $info[] = [trim($vv)=>$v[$vv]];
                } elseif (preg_match("/\s/", $vv)) {
                    $sku[] = [trim($vv)=>$v[$vv]];
                }
            }
            $sku2 = [];
            foreach ($sku as $kk=>$vv) {
                foreach ($vv as $kkk=>$vvv) {
                    $sku2[$kkk]=$vvv;
                }
            }
            $sku2 = json_encode($sku2);
            $info2 = [];
            foreach ($info as $kk=>$vv) {
                foreach ($vv as $kkk=>$vvv) {
                    $info2[$kkk]=$vvv;
                }
            }
            $info2 = json_encode($info2);
            $a2 = [
                'sku'   =>  $sku2,
                'info'  =>  $info2
            ];
            $res[] = array_merge($a1,$a2);
        }
        $data = Db::name('goods')->insertAll($res);
        if ($data) {
            $this->success('您的商品批量发布成功!');
        } else {
            $this->error('您的商品批量发布失败!');
        }
    }

}
